package com.woniuxy.shiroinitest;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

//给予ini文件的自定义域
public class MyRealm extends AuthorizingRealm {

    //进行授权的
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //从这里获取用户名
        String primaryPrincipal=principals.getPrimaryPrincipal()+"";
        //有了用户名，就能去数据库中，找到对应的角色和权限
        //我们随便写几个角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("role1");
        simpleAuthorizationInfo.addRole("role2");
        simpleAuthorizationInfo.addRole("role3");
        simpleAuthorizationInfo.addStringPermission("user:add");
        simpleAuthorizationInfo.addStringPermission("user:update");
        simpleAuthorizationInfo.addStringPermission("user:delete");
        simpleAuthorizationInfo.addStringPermission("user:findOne");
        return simpleAuthorizationInfo;

    }

    //进行认证的
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) token;

        String username=usernamePasswordToken.getUsername();

        //这个密码是 subject.login传进来的！
        String password = new String(usernamePasswordToken.getPassword());

        if(password.equals("123456")){
            SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(username+"这个就是自定义域封装的校长",password,"myRealm");
        //这个凭证 需要交给securityManager，让它帮我管理这个用户登录后的状态和信息！
            return simpleAuthenticationInfo;
        }else{
            throw new AuthenticationException("用户名或密码错误！");
        }
    }
}
